package com.csap.framework.oauth2.level;

import com.csap.framework.oauth2.impl.DataFunction;
import com.csap.framework.redis.RedisUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.function.Function;

/**
 * @Author ycf
 * @Date 2022/3/10 4:42 PM
 * @Version 1.0
 */
@Component
public class RedisCacheImpl<T> implements RedisCache<T> {
    @Resource
    private RedisUtil redisUtil;
    private final long time = 30L;

    private  T getStore(String key, String item, Long eleId, DataFunction<T> dataFunction) {
        Object data = redisUtil.hget(key, item);
        if (data == null) {
            redisUtil.hset(key, item, data = dataFunction.apply(eleId), time);
        } else {
            redisUtil.expire(key, time);
        }
        return (T) data;
    }

    private  T getStore2(String key, String eleId, Function<String, Long> dataFunction) {
        Object data = redisUtil.get(key);
        if (data == null) {
            redisUtil.set(key, data = dataFunction.apply(eleId), time);
        } else {
            redisUtil.expire(key, time);
        }
        return (T) data;
    }

    @Override
    public Long getId(String key, String value, Function<String, Long> dataFunction) {
        return Long.parseLong(getStore2(String.format(KEY_1, key, value), value, dataFunction).toString());
    }

    @Override
    public T executeQuery(Long id, DataFunction<T> gps) {
        return getStore(String.format(KEY, id), gps.strategyType().name(), id, gps);
    }

    @Override
    public T executeUpdate(Long id, T gpsResponse) {
        redisUtil.hset(String.format(KEY, id), GPS_KEY, gpsResponse);
        return gpsResponse;
    }

}
